/**
 * 
 */
package com.jolestar.yayaweibotong.service.impl;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;

import weibo4j.Weibo;
import weibo4j.WeiboException;
import weibo4j.http.AccessToken;
import weibo4j.http.RequestToken;

import com.jolestar.yayaweibotong.ServiceType;
import com.jolestar.yayaweibotong.YaYaAccessToken;
import com.jolestar.yayaweibotong.YaYaRequestToken;
import com.jolestar.yayaweibotong.YayaException;
import com.jolestar.yayaweibotong.service.OAuthService;

/**
 * @author jolestar@gmail.com
 * 
 */
public class SinaOAuthService extends AbstractOAuthService {

	@Override
	public YaYaRequestToken request(HttpServletRequest request) {
		Weibo weibo = new Weibo();
		weibo.setOAuthConsumer(ServiceType.sina.getApiKey(), ServiceType.sina.getApiSecret());
		try {
			RequestToken requestToken = weibo.getOAuthRequestToken(this
					.generateCallback(request, ServiceType.sina));
			return new YaYaRequestToken(requestToken.getToken(),
					requestToken.getTokenSecret(),
					requestToken.getAuthorizationURL());
		} catch (WeiboException e) {
			throw new YayaException(e);
		}
	}

	@Override
	public YaYaAccessToken requestAccessToken(YaYaRequestToken requestToken,
			String verifier) {
		if(StringUtils.isBlank(verifier)){
			throw new YayaException("verifier 码不能为空。");
		}
		Weibo weibo = new Weibo();
		weibo.setOAuthConsumer(ServiceType.sina.getApiKey(), ServiceType.sina.getApiSecret());
		try {
			AccessToken accessToken = weibo.getOAuthAccessToken(
					requestToken.getToken(), requestToken.getTokenSecret(),
					verifier);
			return new YaYaAccessToken(accessToken.getToken(),
					accessToken.getTokenSecret(), Integer.toString(accessToken.getUserId()),
					accessToken.getScreenName());
		} catch (WeiboException e) {
			throw new YayaException(e);
		}
	}

}
